package edu.towson.cosc455.JohnCarloSalter.compiler;

import java.io.*;
import java.util.Scanner;

public class Compiler {

	public static String token;
	static MyLexicalAnalyzer lexer;
	static MySyntaxAnalyzer parser;
	static SemanticAnalyzer generator;
	
	public static void main(String[] args) throws FileNotFoundException {
		File inputFile;
		File outputFile;
		String lolcode;
		PrintWriter outWriter;
		token = "";
		
		//Check that there is only one argument.
		if (args.length != 1) {
			System.err.println("Error: Argument count is not equal to 1.");
			System.exit(-1);
		} else if (!checkExtension(args[0])) {
			System.err.println("Error: File is not of type \".lol\"");
			System.exit(-1);
		}		
		
		inputFile = new File(args[0]);
		outputFile = new File(lolNameToHTMLName(args[0]));
		
		//Set lolcode equal to the contents of our input file.
		lolcode = fileToString(inputFile);
		
		lexer = new MyLexicalAnalyzer(lolcode);
		lexer.getNextToken();
		
		parser = new MySyntaxAnalyzer();
		parser.lolcode();
		
		outWriter = new PrintWriter(outputFile);
		generator = new SemanticAnalyzer(parser.parseTree);
		generator.run(outWriter);
		
		outWriter.close();
		
		System.out.println("******************************");
		System.out.println(".HTML File has been generated.");
		System.out.println("******************************");
	}
	
	//Returns true if the extension of a filename is .lol
	public static boolean checkExtension(String fileName) {
		return fileName.substring(fileName.length() - 4).equals(".lol");		
	}
	
	//Converts the input file to a string.
	public static String fileToString(File inputFile) throws FileNotFoundException {
		String returnString = "";
		Scanner lineScan = new Scanner(inputFile);
		while(lineScan.hasNextLine()) {
			returnString = returnString + lineScan.nextLine();
			if(lineScan.hasNextLine()) {
				returnString = returnString + "\n";
			}
		}
		lineScan.close();
		return returnString;
	}
	
	//Converts the input file name to a .html file name.
	//This method assumes that a proper .lol file name is passed in.
	public static String lolNameToHTMLName(String lolName) {
		String HTMLName = lolName;
		HTMLName = HTMLName.substring(0, HTMLName.length() - 3);
		return HTMLName + "html";
	}

}
